<?php

namespace App\Services;

use App\Http\Resources\Home\StoreResource\StoreCollection;
use App\Http\Resources\Home\StoreResource\StoreJoin;
use App\Models\GoodsClass;
use App\Models\OrderComment;
use App\Models\Store;
use App\Models\StoreClass;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class StoreService extends BaseService
{

    // 获取店铺信息
    public function getHomeStoreList()
    {
        $store_model = new Store;
        $lat = request()->lat ?? '39.56';
        $lng = request()->lng ?? '116.20'; // 默认北京的经纬度

        $distance = "ROUND(6378.138 * 2 * ASIN(SQRT(POW(SIN(('$lat' * PI() / 180 - store_lat * PI() / 180) / 2),2) + COS(40.0497810000 * PI() / 180) * COS(store_lat * PI() / 180) * POW(SIN(('$lng' * PI() / 180 - store_lng * PI() / 180) / 2),2))) * 1000 )  AS distance ";

        $store_model = $store_model->select(DB::raw('*,' . $distance))->withCount(['comments', 'comments as good_comment' => function ($q) {
            $q->whereRaw('(score+agree+speed+service)>=15');
        }]);

        try {
            $params_array = [
                'sort_type' => request()->sort_type,
                'sort_order' => request()->sort_order,
                'class_id' => request()->class_id,
                'keyword' => request()->keyword,
            ];
            if (!empty($params_array)) {
                // 排序
                if (isset($params_array['sort_type']) && !empty($params_array['sort_type'])) {
                    $store_model = $store_model->orderBy($params_array['sort_type'], $params_array['sort_order']);
                } else {
                    $store_model = $store_model->orderBy('distance', 'desc')->orderBy('id', 'desc');
                }
                if (isset($params_array['class_id'])) {
                    $store_model = $store_model->where('class_id', $params_array['class_id']);
                }
                //店铺关键词
                if (isset($params_array['keyword'])) {
                    $store_model = $store_model->where('store_name', 'like', '%' . $params_array['keyword'] . '%');
                }
            }
            $list = $store_model->paginate(request()->per_page ?? 30);
            return $this->format(new StoreCollection($list));

        } catch (\Exception $e) {

            return $this->format_error($e->getMessage());
        }

    }


    // 入驻时获取店铺状态
    public function getStoreVerify($auth = 'user')
    {
        $store_model = new Store();
        $store_info = $store_model->where('user_id', auth($auth)->id())->first();
        if (empty($store_info)) {
            return $this->format_error(__('stores.store_not_defined'));
        }
        return $this->format(new StoreJoin($store_info));
    }

    // 登录用户获取店铺信息
    public function getAuthStoreInfo($where = "")
    {
        $store_info = $this->get_store(false, $where);
        if (empty($store_info)) {
            return $this->format_error(__('stores.store_not_defined'));
        }

        // 地址处理
        $store_info['area_id'] = [$store_info['province_id'], $store_info['city_id'], $store_info['region_id']];

        // 店铺分类
        $choseStoreClasses = $this->getStoreGoodsClasses($store_info['id'])['data'];
        $store_info['chose_store_classes'] = $choseStoreClasses;
        return $this->format($store_info);
    }

    // 获取店铺信息
    public function getStoreInfo($store_id, $select = "")
    {
        $stores_model = new Store();
        if (!empty($select)) {
            $stores_model = $stores_model->select(DB::raw($select));
        }
        $store_info = $stores_model->find($store_id);
        if (empty($store_info)) {
            return $this->format_error(__('stores.store_not_defined'));
        }
        return $this->format($store_info);
    }

    /**
     * 2021/3/12--10:01
     * @param $store_id
     * @return float|int
     * @author:董宗澳
     * @email:2453611300
     * @wechat:DZA74941
     * @QQ:2453611300
     * @web:www.quzha.net
     * @method:getRate
     * @effect:获取店铺评分 百分比
     */
    public function getRate($store_id)
    {
        $store_model = new Store;

        $store_model = $store_model->where('id', $store_id)->withCount(['comments', 'comments as good_comment' => function ($q) {
            $q->whereRaw('(score+agree+speed+service)>=15');
        }])->first();

        return $store_model['comments_count'] == 0 ? 100 : round((($store_model['good_comment'] ?? 0) / $store_model['comments_count']) * 100, 2);
    }

    /**
     * 2021/3/12--10:02
     * @param $store_id
     * @param string $select
     * @return array
     * @author:董宗澳
     * @email:2453611300
     * @wechat:DZA74941
     * @QQ:2453611300
     * @web:www.quzha.net
     * @method:getStoreInfoAndRate
     * @effect:获取评价信息 星级
     */
    public function getStoreInfoAndRate($store_id, $select = "")
    {
        $oc = new OrderComment();
        $store_info = $this->getStoreInfo($store_id, $select)['data'];
        $info = $oc->where('store_id', $store_id)->first([
            DB::raw('avg(score) as scoreAll'),
            DB::raw('avg(agree) as agreeAll'),
            DB::raw('avg(service) as serviceAll'),
            DB::raw('avg(speed) as speedAll'),
        ])->toArray();
        foreach ($info as &$v) {
            $v = intval($v);
        }
//        $store_info['rate'] = $info;
        return $this->format($store_info);
    }

    //获取商品栏目信息
    public function getGoodsClasses()
    {
        $getids = $_GET['ids'];
        $ids = explode(',', $getids);
        $goods_class_model = new GoodsClass();
        $goods_class_list = $goods_class_model
            ->select('id', 'name')
            ->where(['is_show' => 1])
            ->wherein('id', $ids)
            ->get()->toArray();
        return $this->format($goods_class_list);
    }

    // 获取商家拥有的栏目信息
    public function getStoreGoodsClasses($store_id)
    {
//////      // 店铺分类
//    $store_classes_model = new StoreClass();
//    $store_classes = $store_classes_model->where('store_id', $store_id)->first();
//    $class_id = json_decode($store_classes['class_id'], true);
//    $class_name = json_decode($store_classes['class_name'], true);
//    $choseStoreClasses = [];
//    if ($class_id) {
//        foreach ($class_id as $k => $v) {
//            $choseStoreClasses[$k] = [];
//            foreach ($v as $key => $vo) {
//                $choseStoreClasses[$k][$key]['id'] = $vo;
//                $choseStoreClasses[$k][$key]['name'] = $class_name[$k][$key];
//            }
//        }
//    }

        $goods_class_model = new GoodsClass();
        $choseStoreClasses = [];
        $goods_class_list = $goods_class_model
            ->select('id', 'pid', 'name')
            ->where(['is_show' => 1])
            ->orderBy('is_sort', 'asc')
            ->get()->toArray();
        if (request()->level == 1) {
            $data = $this->getChildren($goods_class_list);

            foreach ($data as $v) {
                if (!empty($v['children'])) {
                    foreach ($v['children'] as $level_tow) {
                        if (!empty($level_tow['children'])) {
                            foreach ($level_tow['children'] as $level_three) {
                                $choseStoreClasses[] = $level_three;
                            }
                        }
                    }
                }
            }

        } else {
            $choseStoreClasses = $this->getChildren($goods_class_list);
        }
//        dd([$choseStoreClasses]);
        return $this->format($choseStoreClasses);
    }

    // 递归无线树状结构 多元数组
    protected function getChildren($data, $pid = 0, $lev = 0)
    {
        $arr = [];
        foreach ($data as $v) {

            if ($v['pid'] == $pid) {
                $v['lev'] = $lev;

                $v['children'] = $this->getChildren($data, $v['id'], $lev + 1);
                if (count($v['children']) <= 0) {
                    unset($v['children']);
                }
                if ($v['pid'] == 0) {
                    $arr[][] = $v;
                } else {

                    $arr[] = $v;
                }
            }
        }
        return $arr;
    }

    // 建立店铺
    public function createStore($auth = 'user')
    {
        $store_model = new Store();
        $user_id = auth($auth)->id();
        if ($store_model->where('user_id', $user_id)->exists()) {
            return $this->format_error(__('stores.store_defined'));
        }
        $store_model->user_id = $user_id;
        $store_model->store_verify = 1;
        $store_model->store_status = 0;
        $rs = $store_model->save();
        return $this->format($rs, __('base.success'));
    }

    // 编辑店铺
    public function editStore($store_id)
    {
        $store_model = new Store();
        $store_model = $store_model->find($store_id);

        // 店铺名
        if (isset(request()->store_name)) {
            $store_model->store_name = request()->store_name;
        }
        // 店铺LOGO
        if (isset(request()->store_logo)) {
            $store_model->store_logo = request()->store_logo;
        }
        // 店铺门面
        if (isset(request()->store_face_image)) {
            $store_model->store_face_image = request()->store_face_image;
        }
        // 店铺幻灯片
        if (isset(request()->store_slide)) {
            $store_model->store_slide = request()->store_slide;
        }
        // 店铺手机幻灯片
        if (isset(request()->store_mobile_slide)) {
            $store_model->store_slide = request()->store_mobile_slide;
        }
        // 店铺电话
        if (isset(request()->store_mobile)) {
            $store_model->store_mobile = request()->store_mobile;
        }
        // 店铺描述
        if (isset(request()->store_description)) {
            $store_model->store_description = request()->store_description;
        }
        // 公司名称
        if (isset(request()->store_company_name)) {
            $store_model->store_company_name = request()->store_company_name;
        }
        // 省ID
        if (isset(request()->province_id)) {
            $store_model->province_id = request()->province_id;
        }
        // 市ID
        if (isset(request()->city_id)) {
            $store_model->city_id = request()->city_id;
        }
        // 区ID
        if (isset(request()->region_id)) {
            $store_model->region_id = request()->region_id;
        }
        // 纬度
        if (isset(request()->store_lat)) {
            $store_model->store_lat = request()->store_lat;
        }
        // 经度
        if (isset(request()->store_lng)) {
            $store_model->store_lng = request()->store_lng;
        }
        // 详细地址
        if (isset(request()->store_address)) {
            $store_model->store_address = request()->store_address;
        }
        // 地区信息
        if (isset(request()->area_info)) {
            $store_model->area_info = request()->area_info;
        }
        // 营业执照
        if (isset(request()->business_license)) {
            $store_model->business_license = request()->business_license;
        }
        // 营业执照号码
        if (isset(request()->business_license_no)) {
            $store_model->business_license_no = request()->business_license_no;
        }
        // 法人
        if (isset(request()->legal_person)) {
            $store_model->legal_person = request()->legal_person;
        }
        // 法人电话
        if (isset(request()->store_phone)) {
            $store_model->store_phone = request()->store_phone;
        }
        // 身份证号码
        if (isset(request()->id_card_no)) {
            $store_model->id_card_no = request()->id_card_no;
        }
        // 身份证上
        if (isset(request()->id_card_t)) {
            $store_model->id_card_t = request()->id_card_t;
        }
        // 身份证下
        if (isset(request()->id_card_b)) {
            $store_model->id_card_b = request()->id_card_b;
        }
        // 紧急联系人
        if (isset(request()->emergency_contact)) {
            $store_model->emergency_contact = request()->emergency_contact;
        }
        // 紧急联系人电话
        if (isset(request()->emergency_contact_phone)) {
            $store_model->emergency_contact_phone = request()->emergency_contact_phone;
        }
        // 商家商品栏目
        if (isset(request()->store_classes)) {
            $store_classes_model = new StoreClass();
            $store_classes_info = $store_classes_model->where('store_id', $store_id)->first();
            foreach (request()->store_classes as $k => $v) {
                $class_id[$k] = [];
                $class_name[$k] = [];
                foreach ($v as $vo) {
                    $class_id[$k][] = $vo['id'];
                    $class_name[$k][] = $vo['name'];
                }
            }

            $data = [
                'store_id' => $store_id,
                'class_id' => json_encode($class_id),
                'class_name' => json_encode($class_name),
            ];
            if (empty($store_classes_info)) {
                $store_classes_model->insert($data);
            } else {
                $store_classes_model->where('store_id', $store_id)->update($data);
            }
        }
        try {
            $store_model->save();
        } catch (\Exception $e) {
            Log::channel('qwlog')->debug($e->getMessage());
            return $this->format_error(__('stores.store_edit_error'));
        }

        return $this->format([], __('base.success'));

    }

    // 录入商家信息
    public function addStore($user_id)
    {
        $store_model = new Store();
        // 店铺名
        if (isset(request()->store_name)) {
            $store_model->store_name = request()->store_name;
        }
        // 店铺LOGO
        if (isset(request()->store_logo)) {
            $store_model->store_logo = request()->store_logo;
        }
        // 店铺门面
        if (isset(request()->store_face_image)) {
            $store_model->store_face_image = request()->store_face_image;
        }
        // 店铺幻灯片
        if (isset(request()->store_slide)) {
            $store_model->store_slide = request()->store_slide;
        }
        // 店铺手机幻灯片
        if (isset(request()->store_mobile_slide)) {
            $store_model->store_slide = request()->store_mobile_slide;
        }
        // 店铺电话
        if (isset(request()->store_mobile)) {
            $store_model->store_mobile = request()->store_mobile;
        }
        // 店铺描述
        if (isset(request()->store_description)) {
            $store_model->store_description = request()->store_description;
        }
        // 公司名称
        if (isset(request()->store_company_name)) {
            $store_model->store_company_name = request()->store_company_name;
        }
        // 省ID
        if (isset(request()->province_id)) {
            $store_model->province_id = request()->province_id;
        }
        // 市ID
        if (isset(request()->city_id)) {
            $store_model->city_id = request()->city_id;
        }
        // 区ID
        if (isset(request()->region_id)) {
            $store_model->region_id = request()->region_id;
        }
        // 纬度
        if (isset(request()->store_lat)) {
            $store_model->store_lat = request()->store_lat;
        }
        // 经度
        if (isset(request()->store_lng)) {
            $store_model->store_lng = request()->store_lng;
        }
        // 详细地址
        if (isset(request()->store_address)) {
            $store_model->store_address = request()->store_address;
        }
        // 地区信息
        if (isset(request()->area_info)) {
            $store_model->area_info = request()->area_info;
        }
        // 营业执照
        if (isset(request()->business_license)) {
            $store_model->business_license = request()->business_license;
        }
        // 营业执照号码
        if (isset(request()->business_license_no)) {
            $store_model->business_license_no = request()->business_license_no;
        }
        // 法人
        if (isset(request()->legal_person)) {
            $store_model->legal_person = request()->legal_person;
        }
        // 法人电话
        if (isset(request()->store_phone)) {
            $store_model->store_phone = request()->store_phone;
        }
        // 身份证号码
        if (isset(request()->id_card_no)) {
            $store_model->id_card_no = request()->id_card_no;
        }
        // 身份证上
        if (isset(request()->id_card_t)) {
            $store_model->id_card_t = request()->id_card_t;
        }
        // 身份证下
        if (isset(request()->id_card_b)) {
            $store_model->id_card_b = request()->id_card_b;
        }
        // 紧急联系人
        if (isset(request()->emergency_contact)) {
            $store_model->emergency_contact = request()->emergency_contact;
        }
        // 紧急联系人电话
        if (isset(request()->emergency_contact_phone)) {
            $store_model->emergency_contact_phone = request()->emergency_contact_phone;
        }
        (isset(request()->registered_capital)) && $store_model->registered_capital = request()->registered_capital;//注册资本
        (isset(request()->date_of_establishment)) && $store_model->date_of_establishment = request()->date_of_establishment;//成立日期
        (isset(request()->valid_period)) && $store_model->valid_period = request()->valid_period;//营业执照有效期
        (isset(request()->general_taxpayer_certificate)) && $store_model->general_taxpayer_certificate = request()->general_taxpayer_certificate;//一般纳税人证明
        (isset(request()->email)) && $store_model->email = request()->email;//邮箱
        (isset(request()->class_id)) && $store_model->class_id = request()->class_id;//分类ID
        (isset(request()->community_id)) && $store_model->community_id = request()->community_id;//小区ID
        $store_model->user_id = $user_id;
        // 商家商品栏目
        try {
            $store_model->save();
        } catch (\Exception $e) {
            Log::channel('qwlog')->debug($e->getMessage());
            return $this->format_error(__('stores.store_add_error'));
        }

        return $this->format([], __('base.success'));

    }

    // 编辑店铺状态
    public function editStoreStatus($store_id, $data = [])
    {
        $store_model = new Store();
        $store_model = $store_model->find($store_id);

        // 店铺状态
        if (isset(request()->store_status)) {
            $store_model->store_status = request()->store_status;
        }
        // 审核状态
        if (isset(request()->store_verify)) {
            $store_model->store_verify = request()->store_verify;
        }
        // 审核失败原因
        if (isset(request()->store_refuse_info)) {
            $store_model->store_refuse_info = request()->store_refuse_info;
        }

        // 判断是否存在则修改
        if (isset($data['store_verify'])) {
            $store_model->store_verify = $data['store_verify'];
        }

        try {
            $store_model->save();
        } catch (\Exception $e) {
            Log::channel('qwlog')->debug($e->getMessage());
            return $this->format_error(__('stores.store_edit_error'));
        }

        return $this->format([], __('base.success'));

    }

    /**
     * @Notes 更新的店铺的评分
     * @param $store_id
     * @param $grade
     * @return array
     * @author ypp
     * @date 2021/3/15
     * @time 15:19
     */
    public function setStoreGrade($store_id, $grade)
    {
        $result = Store::where(['id' => $store_id])->update(['grade' => $grade]);
        return $result ? $this->format([]) : $this->format_error('操作失败');
    }

    /**
     * @Notes 获取店铺设置的评分
     * @param $store_id
     * @param ConfigService $configService
     * @return mixed
     * @author ypp
     * @date 2021/3/15
     * @time 15:18
     */
    public function getStoreGrade($store_id)
    {
        //先获取店铺设置的评分
        $grade = Store::where(['id' => $store_id])->value('grade');
        if (!$grade) {
            //如果未设置店铺评分，则查询系统配置的评分
            $grade = (new ConfigService)->getFormatConfig('grade');
        }
        return $grade;

    }
}
